import React, { useMemo, useState, useCallback, useEffect } from 'react';
import { useLocation, useHistory } from 'react-router-dom';
import { Button, Input, Space, Divider, Table, ConfigProvider, message, Modal } from 'antd';
import { LeftOutlined, FileOutlined } from '@ant-design/icons';
import { ColumnsType } from 'antd/es/table/interface';

import './style.scss';
import {
  createIntention,
  modifyIntention,
  getWordModels,
  deleteWordModel,
} from 'admin/servers/servers';
import { WordModelsInfo, ModifyWordModelRequest } from 'admin/schema/WordModel';

import qs from 'query-string';
import AddWordModel from 'admin/components/AddWordModel';
/**词模--改为扩展问，后来词模问题改动较大，单独分出来Actions2；词模逻辑备用 */
const Actions: React.FC = () => {
  // 路由location
  const location = useLocation();
  // URL查询字符串=>对象
  const query = useMemo(() => {
    return qs.parse(location.search);
  }, [location.search]);
  const versionId = Number(query.versionId);
  const history = useHistory();

  // 当前页码
  const [current, setCurrent] = useState<number>(1);
  // 每页条数
  const [pageSize, setPageSize] = useState<number>(10);
  //  数据总数
  const [total, setTotal] = useState<number>(0);
  // Table loading状态
  const [tableLoading, setTableLoading] = useState<boolean>(false);
  // Table数据
  const [wordModels, setWordModels] = useState<WordModelsInfo[]>([]);

  // 意图名称 新增/编辑公用
  const [intentionName, setIntentionName] = useState<string>(
    query.intentionName ? decodeURIComponent(query.intentionName as any) : ''
  );
  // 保存按钮loading
  const [saveLoading, setSaveLoading] = useState<boolean>(false);

  // 意图ID
  const [intentionId, setIntentionId] = useState<number>(
    query.intentionId ? Number(query.intentionId) : 0
  );

  // 删除意图词模：弹框显示
  const [deleteVisible, setDeleteVisible] = useState<boolean>(false);
  // 删除意图词模：意图词模ID
  const [deleteWordModelId, setDeleteWordModelId] = useState<number>(0);
  // 删除意图词模：确认按钮loading
  const [confirmDeleteLoading, setConfirmDeleteLoading] = useState<boolean>(false);

  // 新建词模抽屉弹框 显示/隐藏
  const [addWordModelDrawer, setAddWordModelDrawer] = useState<boolean>(false);
  // 编辑词模弹窗数据
  const [modifyWordModelDrawerData, setModifyWordModelDrawerData] = useState<
    ModifyWordModelRequest | undefined
  >();
  const columns: ColumnsType<WordModelsInfo> = [
    {
      title: '序号',
      dataIndex: 'key',
      key: 'key',
      render: (text, record, index) => index + 1 + pageSize * (current - 1),
    },
    // {
    //   title: "词模",
    //   dataIndex: "wordModel",
    //   key: "wordModel",
    // },
    {
      title: '词模问题',
      dataIndex: 'wordModelDescribe',
      key: 'wordModelDescribe',
    },
    {
      title: '词模类型',
      dataIndex: 'wordModelType',
      key: 'wordModelType',
      render: text => (text === 0 ? '普通意图词模' : '排除意图词模'),
    },
    {
      title: '操作',
      key: 'operation',
      width: 200,
      render: (text, record, index) => (
        <>
          <Button type="link" onClick={() => modifyWordModelAction(index)}>
            编辑
          </Button>
          <Button type="link" onClick={() => deleteWordModelAction(index)}>
            删除
          </Button>
        </>
      ),
    },
  ];

  /**
   * Table数据加载
   */
  const initWordModels = useCallback(async () => {
    if (!intentionId) return;
    setTableLoading(true);
    try {
      const res = await getWordModels({
        pageNo: current,
        pageSize: pageSize,
        intentionId,
      });
      if (res.code === 0) {
        setWordModels(res.data || []);
        setTotal(Number(res.count) || 0);
      } else {
        message.error(`${res.tips}(错误码: ${res.code})`);
      }
      console.log('table--->>>>列表查询数据 res', res);
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
    setTableLoading(false);
  }, [current, intentionId, pageSize]);

  /**
   * 对table数据进行重置操作
   */
  const resetWordModelList = async () => {
    if (current !== 1) {
      setCurrent(1);
      return;
    }
    initWordModels();
  };

  // 数据初始化 && 数据更新
  useEffect(() => {
    initWordModels();
  }, [initWordModels]);

  /**
   * 请求创建意图接口
   */
  const requestCreateIntention = async () => {
    setSaveLoading(true);
    try {
      const res = await createIntention({
        intentionName: intentionName.trim(),
        versionId,
      });
      if (res.code === 0) {
        message.success('新增意图成功');
        // 新增完，保存intentionId-继续编辑意图
        setIntentionId(res.data.intentionId);
      } else {
        message.error(`${res.tips}(错误码: ${res.code})`);
      }
      console.log('createIntention -> res', res);
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
    setSaveLoading(false);
  };

  /**
   * 请求编辑意图接口
   */
  const requestModifyIntention = async () => {
    setSaveLoading(true);
    try {
      const res = await modifyIntention({
        intentionName: intentionName.trim(),
        intentionId,
      });
      if (res.code === 0) {
        message.success('编辑意图成功');
      } else {
        message.error(`${res.tips}(错误码: ${res.code})`);
      }
      console.log('modifyIntention -> res', res);
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
    setSaveLoading(false);
  };

  /**
   * 点击新建词模按钮
   */
  const addWordModelAction = () => {
    if (!intentionId) {
      // 意图还没有创建
      message.warning('请先输入意图名称并保存');
      return;
    }
    setAddWordModelDrawer(true);
  };
  /**
   * 编辑意图词模操作
   * @param index 所编辑数据的index
   */
  const modifyWordModelAction = (index: number) => {
    console.log('编辑意图词模', index);
    setModifyWordModelDrawerData(wordModels[index]);
    setAddWordModelDrawer(true);
  };
  /**
   * 删除意图词模操作
   *  @param idx 所删除数据的index
   */
  const deleteWordModelAction = (index: number) => {
    console.log('删除意图词模', index);
    setDeleteWordModelId(wordModels[index].wordModelId);
    setDeleteVisible(true);
  };

  /**
   * 请求删除意图词模接口
   * @param wordModelId
   */
  const requestDeleteWordModel = async (wordModelId: number) => {
    setConfirmDeleteLoading(true);
    try {
      const res = await deleteWordModel({
        wordModelId,
      });
      if (res.code === 0) {
        message.success('删除意图词模成功');
        resetWordModelList();
      } else {
        message.error(`${res.tips}(错误码: ${res.code})`);
      }
      console.log('deleteWordModel -> res', res);
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
    setDeleteVisible(false);
    setConfirmDeleteLoading(false);
  };
  /**
   * 点击保存意图按钮
   */
  const saveIntentionName = () => {
    if (!intentionName.trim()) {
      message.warning('意图名称不能为空！');
      return;
    }
    console.log(intentionName);
    if (!intentionId) {
      console.log('新增意图！');
      requestCreateIntention();
    } else {
      console.log('编辑意图！');
      requestModifyIntention();
    }
  };

  /**
   * 翻页
   * @param pageNo 点击页码
   */
  const onChagneCurrent = (pageNo: number) => {
    setCurrent(pageNo);
  };
  /**
   *改变每页显示条数
   * @param current 当前页码
   * @param pageSize 每页显示条数
   */
  const onChangePageSize = (current: number, pageSize: number) => {
    setPageSize(pageSize);
  };

  //  分页配置项
  const pagination = {
    total: total,
    showTotal: (total: number) => `共 ${total} 条`,
    current: current,
    pageSize: pageSize,
    showSizeChanger: true,
    onChange: onChagneCurrent,
    onShowSizeChange: onChangePageSize,
  };

  const customizeRenderEmpty = () =>
    //这里面就是我们自己定义的空状态
    !tableLoading && (
      <div style={{ textAlign: 'center' }}>
        <FileOutlined style={{ fontSize: 54, margin: 20 }} />
        <p>新建多条意图词模能帮助系统更准确识别出意图！</p>
        <Button type="primary" style={{ margin: 20 }} onClick={addWordModelAction}>
          新建词模
        </Button>
      </div>
    );
  return (
    <>
      <div>
        <div className="nav">
          <Button
            type="link"
            onClick={() => {
              history.goBack();
            }}
          >
            <LeftOutlined />
            返回
          </Button>
          <div className="title">{intentionId ? '编辑意图' : '新建意图'}</div>
        </div>
        <div className="intentionAction">
          <Space size="large">
            <div>
              <span style={{ color: '#ff0000' }}>*</span>意图名称
            </div>
            <Input
              placeholder="请输入10位以内字数"
              style={{ width: 300 }}
              maxLength={10}
              value={intentionName}
              onChange={e => setIntentionName(e.currentTarget.value)}
            />
            <Button type="primary" loading={saveLoading} onClick={saveIntentionName}>
              保存
            </Button>
            <Button
              onClick={() => {
                history.goBack();
              }}
            >
              取消
            </Button>
          </Space>
        </div>
      </div>
      <div className="wordModel">
        <div>
          <span style={{ fontWeight: 'bold', marginRight: 30 }}>意图词模</span>
          <Button type="primary" onClick={addWordModelAction}>
            新建词模
          </Button>
        </div>
        <Divider style={{ margin: '12px 0' }} />
        <ConfigProvider renderEmpty={customizeRenderEmpty}>
          <Table
            columns={columns}
            loading={tableLoading}
            dataSource={wordModels}
            rowKey="wordModelId"
            pagination={pagination}
          />
        </ConfigProvider>
      </div>
      {/* 删除意图词模弹框 */}
      <Modal
        title="删除意图词模提醒"
        visible={deleteVisible}
        onOk={() => {
          requestDeleteWordModel(deleteWordModelId);
        }}
        confirmLoading={confirmDeleteLoading}
        onCancel={() => {
          setDeleteVisible(false);
        }}
      >
        <p>删除后无法恢复！确定删除吗？</p>
      </Modal>

      {/* 新建、编辑词模抽屉弹框 */}
      <AddWordModel
        show={addWordModelDrawer}
        intentionId={intentionId}
        onClose={() => {
          setAddWordModelDrawer(false);
          setModifyWordModelDrawerData(undefined);
        }}
        onSuccess={() => {
          resetWordModelList();
          setAddWordModelDrawer(false);
          setModifyWordModelDrawerData(undefined);
        }}
        data={modifyWordModelDrawerData}
      />
    </>
  );
};

export default Actions;
